<template>
	<div class="content_container">
		<div class="setting_header">
			<h1>开始写博客吧</h1>
			<span class="logout_btn" v-show="!tokenStr" @click="logout" type="info">点此退出</span>
		</div>
		<el-form ref="articleFormRef" :rules="articleFormRules" :model="articleForm" label-width="100px" label-position="top">
			<el-form-item label="文章标题" prop="title">
				<el-input v-model="articleForm.title"></el-input>
			</el-form-item>
			<el-form-item label="填写简介" prop="summary">
				<el-input type="textarea" v-model="articleForm.summary"></el-input>
			</el-form-item>
			<el-form-item label="选择标签" prop="tag">
				<el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
					{{tag}}
				</el-tag>
				<!-- <el-select v-model="value" multiple filterable allow-create default-first-option placeholder="请选择文章标签">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select> -->
				<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" size="small" @keyup.enter.native="handleInputConfirm"
				@blur="handleInputConfirm">
				</el-input>
				<el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
			</el-form-item>
			<el-form-item label="选择分类" prop="classifica">
				<el-select @change="classificaValueChange" v-model="classificaValue" clearable placeholder="请选择文章分类">
					<el-option v-for="item in allClassificas" :key="item.classifica_id" :value="item.classifica_name">
					</el-option>
				</el-select>
				<el-input class="input-new-tag" v-if="inputClassificaVisible" v-model="inputClassificaValue" size="small"
				@keyup.enter.native="handleInputClassificaConfirm" @blur="addClassifica">
				</el-input>
				<el-button v-else class="button-new-tag" size="small" @click="showClassificaInput">+ New Class</el-button>
			</el-form-item>
			<el-form-item label="选择日期">
				<el-date-picker type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" v-model="articleForm.created_time"
				style="width: 30%;"></el-date-picker>
			</el-form-item>
			<el-form-item label="文章内容">
				<!-- 图片上传组件辅助-->
				<!-- <el-upload class="avatar-uploader-ui" :action="serverUrl" name="file" accept="image/png,image/jpg,image/jpeg"
          :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUpload">
        </el-upload>
        <el-form-item label="图文信息录入" v-loading="quillUpdateImg">
          <div class="edit_container">
            <span>建议上传图片宽度=800 px，图片大小不能大于1M</span>
            <quill-editor v-model="articleForm.content" ref="myQuillEditor" class="editor" :options="editorOption"
              @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item> -->
				<quill-editor v-model="articleForm.content"></quill-editor>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="addArticle">发布博客</el-button>
				<el-button>取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				classificaValue: "",
				allClassificas: [],
				tokenStr: "",
				dynamicTags: [],
				articleForm: {
					title: "",
					summary: "",
					created_time: "",
					tag: [],
					classifica: "",
					content: ""
				},
				articleFormRules: {
					title: [{
							required: true,
							message: "请输入文章标题",
							trigger: "blur"
						},
						{
							min: 3,
							max: 20,
							message: "长度在 3 到 10 个字符",
							trigger: "blur"
						}
					],
					summary: [{
						required: true,
						message: "请输入文章简介",
						trigger: "blur"
					}]
				},
				inputVisible: false,
				inputValue: "",
				inputClassificaVisible: false,
				inputClassificaValue: "",
				quillUpdateImg: false,
				editorOption: {
					placeholder: "请在这里输入",
					modules: {
						toolbar: {
							// ['image']
							container: [
								["image"]
							],
							handlers: {
								image: function(value) {
									if (value) {
										// 触发input框选择图片文件
										document.querySelector(".avatar-uploader-ui input").click();
									} else {
										this.quill.format("image", false);
									}
								}
							}
						}
					}
				}
			};
		},
		methods: {
			logout() {
				window.sessionStorage.clear();
				this.$router.push("/login");
			},
			async getAllClassificas() {
				const {
					data: res
				} = await this.$http.get("classifica");
				if (res.meta.status != 200) return this.$message.error("获取分类失败");
				this.allClassificas = res.data.classificas;
			},
			async addClassifica(classifica) {
				const {
					data: res
				} = await this.$http.post("classifica", {
					classifica_name: classifica
				});
				if (res.meta.status != 201) return this.$message.error("添加分类失败");
				this.$message.success("添加分类成功");
				this.getAllClassificas();
			},
			showInput() {
				this.inputVisible = true;
			},
			showClassificaInput() {
				this.inputClassificaVisible = true;
			},
			classificaValueChange() {
				this.articleForm.classifica = this.classificaValue;
				console.log(this.articleForm.classifica);
			},
			handleInputClassificaConfirm() {
				let inputClassificaValue = this.inputClassificaValue;
				if (inputClassificaValue) {
					this.addClassifica(inputClassificaValue);
				}
			},
			handleClose(tag) {
				this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
			},
			handleInputConfirm() {
				let inputValue = this.inputValue;
				if (inputValue) {
					this.dynamicTags.push(inputValue);
				}
				this.articleForm.tag = this.dynamicTags;
				this.inputVisible = false;
				this.inputValue = "";
			},
			addArticle() {
				this.$refs.articleFormRef.validate(async valid => {
					if (!valid) return;
					const {
						data: res
					} = await this.$http.post(
						"article",
						this.articleForm
					);
					console.log(res);
					if (res.meta.status !== 201) return this.$message.error("发布失败");
					this.$message.success("发布成功");
					this.$router.push("/home");
				});
			},
			// 富文本图片上传前
			beforeUpload(file) {
				const is1M = file.size / 1024 / 1024 < 1; // 限制小于1M
				if (!is1M) {
					this.$message.error("图片大小不可超过1MB");
					return console.log("图片大小不能超过1MB");
				}

				return new Promise((resolve, reject) => {
					let width = 800; // 限制图片尺寸为800
					let _URL = window.URL || window.webkitURL;
					let img = new Image();
					img.onload = () => {
						const valid = img.width === width;
						if (!valid) {
							this.$message.error("图片尺寸限制宽度为800px，大小不可超过1MB");
							return reject();
						}
						return resolve();
					};
					img.src = _URL.createObjectURL(file);
				});
			},
			uploadSuccess(res) {
				// res为图片服务器返回的数据
				// 获取富文本组件实例
				let quill = this.$refs.myQuillEditor.quill;
				// 如果上传成功
				if (res.status === "success" && res.uri !== null) {
					// 获取光标所在位置
					let length = quill.getSelection().index;
					// 插入图片  res.info为服务器返回的图片地址
					quill.insertEmbed(length, "image", res.uri);
					// 调整光标到最后
					quill.setSelection(length + 1);
				} else {
					this.$message.error("图片插入失败");
				}
				// loading动画消失
				this.quillUpdateImg = false;
			},

			// 富文本图片上传失败
			uploadError() {
				// loading动画消失
				this.quillUpdateImg = false;
				this.$message.error("图片插入失败");
			}
		},
		created() {
			let tokenStr = this.tokenStr;
			tokenStr = window.sessionStorage.getItem("token");
			if (!tokenStr) return this.$router.push("/login");
			this.getAllClassificas();
		}
	};
</script>

<style lang="less" scoped>
	.content_container {
		max-width: 900px;
		margin: 15px auto;
	}

	.el-form {
		color: rgb(255, 255, 255);
		opacity: 0.6;
	}

	.el-form-item__label {
		color: rgb(255, 255, 255);
	}

	.setting_header {
		position: relative;
		margin-bottom: 40px;
	}

	.logout_btn {
		top: 10px;
		opacity: 0.3;
		right: 20px;
		cursor: pointer;
		position: absolute;

		&:hover {
			color: lightseagreen;
			text-decoration: underline;
		}
	}

	.el-tag+.el-tag {
		margin-left: 10px;
	}

	.button-new-tag {
		margin-left: 10px;
		height: 32px;
		line-height: 30px;
		padding-top: 0;
		padding-bottom: 0;
	}

	.input-new-tag {
		width: 90px;
		margin-left: 10px;
		vertical-align: bottom;
	}

	.quill-editor {
		display: flex;
		flex-flow: column;
		padding: 10px;
		border-radius: 1%;
		// min-height: 300px;
		color: rgba(0, 0, 0);
		background-color: rgb(255, 255, 255);
	}

	.ql-container .quill-editor{
		height: 300px;
	}

</style>
